package com.lagou.sqlsession;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库连接事务管理
 */
public class JdbcTransaction implements Transaction{

    protected  Connection connection;
    protected final DataSource dataSource;

    public JdbcTransaction(Connection connection, DataSource dataSource) {
        this.connection = connection;
        this.dataSource = dataSource;
    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    @Override
    public Connection getConnection() throws SQLException {
        if (connection == null) {//连接对象为空，重新获取数据库连接
            openConnection();
        }
        return connection;

    }

    /**
     * 获取数据库连接
     * @throws SQLException
     */
    protected void openConnection() throws SQLException {
        connection = dataSource.getConnection();
    }

    @Override
    public void commit() throws SQLException {
        if(connection==null)
            throw  new RuntimeException("数据库连接对象为空");
        connection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        connection.rollback();
    }
}
